package com.valveinspectionsys.base;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.valveinspectionsys.dbhelp.DBOpenHelper;
import com.valveinspectionsys.dbhelp.DbTableName;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.povo.CompetencePOVO;
import com.valveinspectionsys.povo.DeviceItem;
import com.valveinspectionsys.povo.DeviceSubItem;
import com.valveinspectionsys.util.FileNameUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

public class BaseDao {
    private SQLiteDatabase db;

    private DBOpenHelper helper;

    private String userId;

    private CompetencePOVO comp;

    public SQLiteDatabase getDb() {
	return db;
    }

    public void setDb(SQLiteDatabase db) {
	this.db = db;
    }

    public BaseDao(Context context, String SqliteName) {
	helper = new DBOpenHelper(context, SqliteName);
	SharedPreferenceUtil sh = new SharedPreferenceUtil(context);
	this.userId = sh.getValue(XmlNameHelper.userID);
	comp = new CompetencePOVO();
	comp.setUserID(userId);
	comp.setAddTuwen(sh.getBoolean(XmlNameHelper.addTuwen));
	comp.setBindingTag(sh.getBoolean(XmlNameHelper.BindingTag));
	comp.setGeneralReading(sh.getBoolean(XmlNameHelper.GeneralReading));
	comp.setReBindingTag(sh.getBoolean(XmlNameHelper.ReBindingTag));
	comp.setReTuwen(sh.getBoolean(XmlNameHelper.ReTuwen));

	db = helper.getWritableDatabase();

    }

    /**
     * 批量添加数据
     * 
     * @param value
     *            数据
     * @param table
     *            表名
     * @return
     */
    public boolean insertALL(List<ContentValues> value, String table) {

	db.beginTransaction();
	for (int i = 0; i < value.size(); i++) {
	    long id = db.insert(table, null, value.get(i));
	    if (id < 1) {
		return false;
	    }

	}
	db.setTransactionSuccessful();
	db.endTransaction();
	return true;

    }

    /**
     * 添加一条数据
     * 
     * @param values
     * @param table
     * @return
     */
    public boolean insert(ContentValues values, String table) {
	boolean b = false;
	long id = db.insert(table, null, values);
	if (id > 1) {
	    b = true;
	}
	return b;
    }

    /**
     * 添加一条数据
     * 
     * @param values
     * @param table
     * @return 返回当前添加数据的ID
     */
    public int insertID(ContentValues values, String table) {
	int id = 0;
	long k = db.insert(table, null, values);
	if (k > 0) {
	    String sql = "select max(_id) as maxid from " + table;
	    Cursor cursor = db.rawQuery(sql, null);
	    if (cursor.moveToNext()) {
		id = cursor.getInt(cursor.getColumnIndex("maxid"));
	    }
	    if (cursor != null) {
		cursor.close();
	    }
	}
	return id;
    }

    /**
     * 删除所有数据
     * 
     * @param table
     * @return
     */
    public boolean delectAll(String table) {
	boolean b = false;
	long id = db.delete(table, "_id>?", new String[] { "0" });
	FileNameUtil  f=new FileNameUtil();
	f.delectFile("order");
	db.delete(DbTableName.RESOURCES, "status='-1'", null);
	if (id > 0) {
	    b = true;
	}
	return b;
    }

    /**
     * 删除一条数据
     * 
     * @param id
     * @param table
     * @return
     */
    public boolean delect(String id, String table) {
	boolean b = false;
	long ids = db.delete(table, "_id=?", new String[] { id });
	if (ids > 0) {
	    b = true;
	}
	return b;
    }

    /**
     * 通过ID更新一条数据
     * 
     * @param id
     * @param table
     * @param values
     * @return
     */
    public boolean modify(String id, String table, ContentValues values) {
	boolean b = false;

	long k = db.update(table, values, "_id=?", new String[] { id });
	if (k > 0) {
	    b = true;
	}
	return b;
    }

    /**
     * 查询总条数
     * 
     * @param db
     * @param sql
     * @return
     */
    public int getCount(String sql) {
	int i = 0;

	Cursor cursor = db.rawQuery(sql, null);

	if (cursor.moveToNext()) {
	    i = cursor.getCount();
	}
	if (cursor != null) {
	    cursor.close();
	}
	return i;

    }

    /**
     * 分页
     * 
     * @param db
     * @param firstResult
     *            从第几条数据开始查询
     * @param maxResult
     *            每页显示多少条记录
     * @param sql
     * @return
     */
    public Cursor getAllItems(int firstResult, int maxResult, String sql) {

	System.out.println("------firstResult--------" + firstResult);
	sql = sql + " limit ?,?";

	Cursor mCursor = db.rawQuery(sql, new String[] { String.valueOf(firstResult), String.valueOf(maxResult) });
	System.out.println(mCursor == null);
	return mCursor;
    }

    /**
     * 通过ID批量修改数据
     * 
     * @author king
     * @param map
     *            key:ID,
     * @param tableName
     *            表名
     */
    public boolean modifyAll(Map<String, ContentValues> map, String tableName) {

	db.beginTransaction();
	for (String values : map.keySet()) {
	    int k = db.update(tableName, map.get(values), "_id=?", new String[] { values });
	    if (k < 1) {
		return false;
	    }
	}
	db.setTransactionSuccessful();
	db.endTransaction();
	return true;

    }

    /**
     * 关闭连接
     */
    public void close() {
	if (db != null && db.isOpen()) {
	    db.close();
	}
    }

    public String getUserId() {
	return userId;
    }

    public void setUserId(String userId) {
	this.userId = userId;
    }

    public CompetencePOVO getComp() {
	return comp;
    }

    /**
     * 判断字符串是否为数字
     * 
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
	if (str.matches("\\d*")) {
	    return true;
	} else {
	    return false;
	}
    }

    /**
     * 得到抄表状态
     * 
     * @param type
     * @return
     */
    public String getCopyStatus(String type) {
	String copystatus = "未抄";
	if (type.equals("1")) {
	    copystatus = "二次抄表";
	} else if (type.equals("2")) {
	    copystatus = "不能抄";
	} else if (type.equals("3")) {
	    copystatus = "已抄";
	}

	return copystatus;
    }

    /**
     * 得到数据库抄表状态
     * 
     * @param type
     * @return
     */
    public String getDbCopyStatus(String type) {
	String copystatus = "0";
	if (type.equals("二次抄表")) {
	    copystatus = "1";
	} else if (type.equals("不能抄")) {
	    copystatus = "2";
	} else if (type.equals("已抄")) {
	    copystatus = "3";
	}
	return copystatus;
    }

    public boolean isaddDeviceitem() {
	boolean b = false;

	String sql = "select count(_id)  as total from deviceItem";
	Cursor cursor = db.rawQuery(sql, null);
	if (cursor.moveToNext()) {
	    if (cursor.getInt(cursor.getColumnIndex("total")) == 8) {
		b = true;
	    }
	}

	if (b) {
	    String sql2 = "select count (_id) as total from devicesubitem";
	    cursor = db.rawQuery(sql2, null);
	    if (cursor.moveToNext()) {
		if (cursor.getInt(cursor.getColumnIndex("total")) == 18) {
		    b = true;
		} else {
		    b = false;
		}
	    } else {
		b = false;
	    }

	}
	if (cursor != null) {
	    cursor.close();
	}
	return b;
    }

    /**
     * 通过 一个字符解析得到保养项目
     * 
     * @param info
     * @return
     */
    public List<DeviceItem> queryDeviceItem(String info) {
	List<DeviceItem> list = new ArrayList<DeviceItem>();

	String[] str = info.split(",");
	if (str[0].equals("1")) {
	  
	    DeviceItem item = new DeviceItem();
	    item.setDeviceItemName("防腐");
	    item.setDeviceItemNumber("1");
	    List<DeviceSubItem> l = new ArrayList<DeviceSubItem>();
	    DeviceSubItem subitem0 = new DeviceSubItem();
	    subitem0.setDeviceItemNumbeer("1");
	    subitem0.setName("请选择");
	    subitem0.setNumber("0");
	    l.add(subitem0);
	    DeviceSubItem subitem = new DeviceSubItem();
	    subitem.setDeviceItemNumbeer("1");
	    subitem.setName("无需保养");
	    subitem.setNumber("1");
	    l.add(subitem);
	    DeviceSubItem subitem1 = new DeviceSubItem();
	    subitem1.setDeviceItemNumbeer("1");
	    subitem1.setName("保养完成");
	    subitem1.setNumber("2");
	    l.add(subitem1);
	    item.setSubitem(l);
	    list.add(item);
	}
	if (str[1].equals("1")) {

	    DeviceItem item = new DeviceItem();
	    item.setDeviceItemName("润滑");
	    item.setDeviceItemNumber("2");
	    List<DeviceSubItem> l = new ArrayList<DeviceSubItem>();
	    DeviceSubItem subitem0 = new DeviceSubItem();
	    subitem0.setDeviceItemNumbeer("2");
	    subitem0.setName("请选择");
	    subitem0.setNumber("0");
	    l.add(subitem0);
	    DeviceSubItem subitem = new DeviceSubItem();
	    subitem.setDeviceItemNumbeer("2");
	    subitem.setName("无需保养");
	    subitem.setNumber("1");
	    l.add(subitem);
	    DeviceSubItem subitem1 = new DeviceSubItem();
	    subitem1.setDeviceItemNumbeer("2");
	    subitem1.setName("保养完成");
	    subitem1.setNumber("2");
	    l.add(subitem1);
	    item.setSubitem(l);
	    list.add(item);

	}
	if (str[2].equals("1")) {

	    DeviceItem item = new DeviceItem();
	    item.setDeviceItemName("导阀保养");
	    item.setDeviceItemNumber("3");
	    List<DeviceSubItem> l = new ArrayList<DeviceSubItem>();
	    DeviceSubItem subitem0 = new DeviceSubItem();
	    subitem0.setDeviceItemNumbeer("3");
	    subitem0.setName("请选择");
	    subitem0.setNumber("0");
	    l.add(subitem0);
	    DeviceSubItem subitem = new DeviceSubItem();
	    subitem.setDeviceItemNumbeer("3");
	    subitem.setName("无需保养");
	    subitem.setNumber("1");
	    l.add(subitem);
	    DeviceSubItem subitem1 = new DeviceSubItem();
	    subitem1.setDeviceItemNumbeer("3");
	    subitem1.setName("保养完成");
	    subitem1.setNumber("2");
	    l.add(subitem1);
	    item.setSubitem(l);
	    list.add(item);

	}
	return list;

    }

    public String DeviceItemInfo(String info, String str) {
	String result = "";
	if (TextUtils.isEmpty(str) || str.indexOf(",") < 1) {
	    // String sql=" select * from deviceItem where number in (";
	    // String[] str1=info.split(",");
	    // for(int i=0;i<str1.length;i++){
	    // sql=sql+str1[i]+",";
	    // }
	    // sql=sql.substring(0, sql.length()-1);
	    // sql=sql+")";
	    // Cursor cursor=db.rawQuery(sql, null);
	    // while(cursor.moveToNext()){
	    //
	    // }
	    return result;
	}
	String[] str1 = info.split(",");
	String[] str2 = str.split(",");

	Cursor cursor = null;
	for (int i = 0; i < str1.length; i++) {
	    if (!str1.equals("0")) {
		String sql = "select di.[name] as diname,ds.[name] as dsname from deviceItem di,devicesubitem ds where di.[number]=ds.[itemNumber] and " + " di.[number]='"
			+ (i + 1) + "' and ds.[number]='" + str2[i] + "'";
		cursor = db.rawQuery(sql, null);
		if (cursor.moveToNext()) {
		    result = result + "  " + cursor.getString(cursor.getColumnIndex("diname")) + ": " + cursor.getString(cursor.getColumnIndex("dsname"));
		}
	    }
	}
	if (cursor != null) {
	    cursor.close();
	}
	return result;

    }

    /**
     * 巡检、保养项目
     * @param info
     * @return
     */
    public List<DeviceItem> queryItems(String info) {
	List<DeviceItem> list = new ArrayList<DeviceItem>();
	String sql = "select di.[_id] as itemid, di.[name] as itemname,di.[number] as itemnumber,di.[type],di.[forcedpictures]"
		+ ",dsi.[name] as subname,dsi.[number] as subnumber,dsi.[itemNumber],dsi.[_id] as subid"
		+ " from deviceItem di,devicesubitem dsi where di.[number]=dsi.[itemNumber] and di.[type]='" + 1 + "' " + " and di.[number] in (";
	String[] s=info.split(",");
	for (int i = 0; i < s.length; i++) {
	   if(s[i].equals("1")){
	       sql=sql+(i+1)+",";
	   }
	}
	sql = sql.substring(0, sql.length() - 1);
	sql = sql + ") order by di.number";
	System.out.println("-------查询项目SQL--------"+sql);
	Cursor cursor = db.rawQuery(sql, null);
	DeviceItem item = null;
	List<DeviceSubItem> subitem = null;
	while (cursor.moveToNext()) {
	    String itemid = cursor.getString(cursor.getColumnIndex("itemid"));
	    if (list.size() == 0 || !list.get(list.size() - 1).getDeviceItemID().equals(itemid)) {
		item = new DeviceItem();
		subitem = new ArrayList<DeviceSubItem>();
		item.setDeviceItemID(itemid);
		item.setDeviceItemName(cursor.getString(cursor.getColumnIndex("itemname")));
		item.setDeviceItemNumber(cursor.getString(cursor.getColumnIndex("itemnumber")));
		item.setDeviceItemType(cursor.getString(cursor.getColumnIndex("type")));
		item.setForcedpictures(cursor.getString(cursor.getColumnIndex("forcedpictures")));
		list.add(item);
		DeviceSubItem sui=new DeviceSubItem();
		sui.setDeviceItemNumbeer(item.getDeviceItemNumber());
		sui.setName("请选择");
		sui.setNumber("0");
		subitem.add(sui);
	    }
	    DeviceSubItem suitem = new DeviceSubItem();
	    suitem.setDeviceItemNumbeer(cursor.getString(cursor.getColumnIndex("itemNumber")));
	    suitem.setId(cursor.getString(cursor.getColumnIndex("subid")));
	    suitem.setName(cursor.getString(cursor.getColumnIndex("subname")));
	    suitem.setNumber(cursor.getString(cursor.getColumnIndex("subnumber")));
	    subitem.add(suitem);
	    item.setSubitem(subitem);
	}
	if (cursor != null) {
	    cursor.close();
	}
	
	return list;
    }
    
    /**
     * 通过数据库字段得到显示所用设备类型
     * @param info
     * @return
     */
    public String ViewDeviceType(int  info){
	
	String[]  ss=new String[]{"闸阀","蝶阀","消火栓","减压阀","排气阀","止回阀","堵板"};
	
	return ss[info];
	
    }
    
    /**
     * 通过解析字符串得到巡检上传数据
     * @param info
     * @return
     */
    public String uproutingData(String info,String data){
	String str="";
	String[]  s=info.split(",");
	String[]  ss=data.split(",");
	int k=0;
	for(int i=0;i<s.length;i++){
	    if(s[i].equals("0")){
		str=str+"0";
	    }else{
		str=str+ss[k];
		k++;
	    }
	}
	System.out.println("----111111111111----"+str);
	return str;
    }
    
    /**
     * 删除除每一类弄数据
     * @param type（1巡检 2保养 3维修 4抢修）
     * @return
     */
    public boolean delectDeviceAll(String type){
	boolean b=false;
	 FileNameUtil   f=new FileNameUtil();
	  if(type.equals("1")){
	      db.delete(DbTableName.DEVICEINFO, "operationtype='0' or operationtype='1' ", null);
	      db.delete(DbTableName.DEVICELIST, "operationtype='0' or operationtype='1'", null);
	      db.delete(DbTableName.NAVIGATION, "type='0' or type='1'", null);
	      db.delete(DbTableName.RESOURCES, "status='0' or status='1'", null);
	      f.delectFile("routdeviceimg");
	  }else{
	      db.delete(DbTableName.DEVICEINFO, "operationtype='"+type+"'", null);
	      db.delete(DbTableName.DEVICELIST, "operationtype='"+type+"'", null);
	      db.delete(DbTableName.NAVIGATION, "type='"+type+"'", null);
	      db.delete(DbTableName.RESOURCES, "status='"+type+"'", null);
	  }
	  if(type.equals("2")){
	      f.delectFile("maintainimg");
	      
	  }else if(type.equals("3")){
	      f.delectFile("repairimg");
	      db.delete(DbTableName.REPAIR, "repairtype='1'", null);
	  }else if(type.equals("4")){
	      db.delete(DbTableName.REPAIR, "repairtype='2'", null);
	      f.delectFile("rushrepair");
	  }
	return b;
    }
}
